<template>
  <div>
    <el-dialog title="组织机构——多选" :visible="visible" width="400px" append-to-body @close="close">
      <el-input v-model="searchValue" placeholder="请输入关键字过滤" style="margin-bottom:10px" />

      <el-tree
        ref="tree"
        :data="treeData"
        node-key="id"
        show-checkbox
        :default-expanded-keys="defaultExpandedKeys"
        :filter-node-method="filterNode"
        :default-checked-keys="checkedNodesId"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {

  data() {
    return {
      visible: false,
      treeData: [],
      searchValue: '',
      defaultExpandedKeys: [],
      selectedValue: [],
      checkedNodesId: []

    }
  },
  watch: {
    searchValue(value) {
      this.$refs.tree.filter(value)
    }
  },

  methods: {
    show(idList) {
      this.searchValue = ''
      this.defaultExpandedKeys = []
      this.selectedValue = idList
      this.loadTree()
      this.visible = true
    },
    loadTree() {
      this.$api.system.organization.tree()
        .then(res => {
          this.treeData = res.data
          // 默认展开根节点
          this.defaultExpandedKeys.push(this.treeData[0].id)

          this.checkedNodesId = []
          this.getLeafNodeChecked(this.treeData)
          this.$refs.tree.setCheckedKeys(this.checkedNodesId)
        })
    },
    close() {
      this.visible = false
    },
    confirm() {
      this.$emit('ok', this.$refs.tree.getCheckedKeys())
      this.visible = false
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getLeafNodeChecked(node) {
      // 遍历树节点，设置
      for (const treeNode of node) {
        // 如果节点有子节点，那他的选中状态不被考虑，继续往下找
        if (treeNode.children && treeNode.children.length > 0) {
          this.getLeafNodeChecked(treeNode.children)
        } else {
          // 是叶子节点，如果是check状态就记录
          if (this.selectedValue.includes(treeNode.id)) {
            this.checkedNodesId.push(treeNode.id)
          }
        }
      }
    }

  }
}

</script>

<style scoped>
</style>
